import hashlib
import bcrypt
from datetime import datetime

from flask import request
from flask_restx import Namespace, Resource, fields
from flask_jwt_extended import jwt_required

# 导入 User 模型
from app1.models import Zbfwbuser
from app1 import db
from app1 import api
from app1.utils import check_permission, format_response_page

# 创建 Flask-RESTx 命名空间
ns1 = Namespace('users', description='User operations')

# 定义用户模型
user_delete_model = ns1.model('User_delete', {
    't_zbfwb_user_name': fields.String(required=True, description='Username'),
})

# 定义用户模型
user_login_model = ns1.model('User_login', {
    't_zbfwb_user_name': fields.String(required=True, description='Username'),
    't_zbfwb_user_passwd': fields.String(required=True, description='Password')
})

# 使用 Flask-RESTx 定义用户数据模型
user_model = ns1.model('Zbfwbuser', {
    't_zbfwb_user_id': fields.Integer(readOnly=True, description='The user unique identifier'),
    't_zbfwb_user_name': fields.String(required=True, description='User name'),
    't_zbfwb_user_passwd': fields.String(required=True, description='User password'),
    # 't_zbfwb_user_createtime': fields.DateTime(description='User creation time'),
    # 't_zbfwb_user_updatetime': fields.DateTime(description='User update time')
})

page_model = ns1.model('page', {
    'page': fields.Integer(required=True, description='start page', default=1),
    'per_page': fields.Integer(required=True, description='per page', defualt=20),
    'max_page': fields.Integer(required=True, description='max page', default=50),
})

page_data_model = ns1.model('pagedata', {
    'has_next': fields.Boolean(),  # has_next: 是否还有下一页
    'has_prev': fields.Boolean(),  # has_prev: 是否还有上一页
    'items': fields.List(fields.Nested(user_model)),  # items: 返回当前页的所有内容
    'next': fields.List(fields.Nested(user_model)),  # next(error_out=False): 返回下一页的Pagination对象
    'prev': fields.List(fields.Nested(user_model)),  # prev(error_out=False): 返回上一页的Pagination对象
    'page': fields.Integer(),  # page: 当前页的页码(从1开始)
    'pages': fields.Integer(),  # pages: 总页数
    'per_page': fields.Integer(),  # per_page: 每页显示的数量
    'prev_num': fields.Integer(),  # prev_num: 上一页页码数
    'next_num': fields.Integer(),  # next_num: 下一页页码数
    # query: 返回
    'total': fields.Integer()  # total: 查询返回的记录总数
})

# 定义外层的响应翻页返回
response_user_page_data_model = ns1.model('Response_user_page_data', {
    "message": fields.String(description='翻页查询结果'),
    "result": fields.Nested(page_data_model),
    "status": fields.Integer(description='返回状态', default=200),  # 查询返回状态,
    "timestamp": fields.String(description='时间戳', default=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))),  # 时间戳
})

# 定义外层的响应模型
response_user_model = ns1.model('Response_User', {
    'message': fields.Nested(ns1.model('Message_User', {
        "result": fields.Integer(description='查询结果返回值'),
        "result_text": fields.String(description='查询结果信息'),
        'count': fields.Integer(description='查询结果返回数据条数'),
        'data': fields.List(fields.Nested(user_model))
    }))
})


def md5_hash(password):
    """使用MD5对密码进行加密"""
    return hashlib.md5(password.encode('utf-8')).hexdigest()


# 创建用户资源
@ns1.route('/user')
class UserResource(Resource):
    @jwt_required()
    @ns1.marshal_with(response_user_model)
    def get(self):
        """Get a list of all users"""
        # 检查权限（假设权限是 'view_users'）
        if not check_permission([4]):
            return {'message': {'result': 403, 'result_text': 'Permission denied', 'count': 0, 'data': []}}, 403

        # 查询所有用户
        users = Zbfwbuser.query.all()

        # 构建响应数据
        response = {
            'message': {
                'result': 200,  # 查询成功
                'result_text': 'Users retrieved successfully',
                'count': len(users),
                'data': users  # 返回的用户数据
            }
        }

        return response

    @jwt_required()
    @ns1.expect(user_login_model)
    @ns1.marshal_with(response_user_model)
    def post(self):
        """Create a new user"""
        # 检查权限（假设权限是 'create_user'）
        if not check_permission([1]):
            return {'message': {'result': 403, 'result_text': 'Permission denied', 'count': 0, 'data': []}}, 403

        data = api.payload

        """check username dup"""
        user_name = data['t_zbfwb_user_name']

        existing_user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
        if existing_user:
            # api.abort(400, f"User with user_name {user_name} already exists")
            response = {
                'message': {
                    'result': 400,  # 创建成功
                    'result_text': f'User  {user_name}  already exists',
                    'count': 1,
                    'data': [existing_user]  # 返回创建的用户数据
                }
            }

            return response

        # 生成唯一的 user_id，例如使用 UUID
        import uuid
        new_user_id = str(uuid.uuid4().int)[0:8]

        # 对密码进行MD5加密
        hashed_password = md5_hash(data['t_zbfwb_user_passwd'])

        new_user = Zbfwbuser(
            t_zbfwb_user_id=new_user_id,
            t_zbfwb_user_name=data['t_zbfwb_user_name'],
            t_zbfwb_user_passwd=hashed_password
        )

        db.session.add(new_user)
        db.session.commit()

        # 构建响应数据
        response = {
            'message': {
                'result': 201,  # 创建成功
                'result_text': 'User created successfully',
                'count': 1,
                'data': [new_user]  # 返回创建的用户数据
            }
        }

        return response, 201


@ns1.route('/updateuser')
class UserUpdateResource(Resource):
    @jwt_required()
    @ns1.expect(user_login_model)
    @ns1.marshal_with(response_user_model)
    def post(self):
        """Update a user"""
        # 检查权限（假设权限是 'create_user'）
        if not check_permission([3]):
            return {'message': {'result': 403, 'result_text': 'Permission denied', 'count': 0, 'data': []}}, 403

        data = api.payload

        user_name = data['t_zbfwb_user_name']
        # 对密码进行MD5加密
        hashed_password = md5_hash(data['t_zbfwb_user_passwd'])

        print(user_name)
        user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()

        print(user)
        if user:
            print("debgu1")
            user.t_zbfwb_user_passwd = hashed_password
            db.session.commit()
        else:
            print("debug2")
            # 构建响应数据
            response = {
                'message': {
                    'result': 400,  # 创建成功
                    'result_text': 'User not existed',
                    'count': 0,
                    'data': []  # 返回创建的用户数据
                }
            }
            return response

        # 构建响应数据
        response = {
            'message': {
                'result': 201,  # 创建成功
                'result_text': 'User updated successfully',
                'count': 1,
                'data': [user]  # 返回创建的用户数据
            }
        }

        return response


@ns1.route('/deleteuser')
class UserDeleteResource(Resource):
    @jwt_required()
    @ns1.expect(user_delete_model)
    @ns1.marshal_with(response_user_model)
    def post(self):
        """Delete a user"""
        # 检查权限（假设权限是 'create_user'）
        if not check_permission([2]):
            return {'message': {'result': 403, 'result_text': 'Permission denied', 'count': 0, 'data': []}}, 403

        data = api.payload

        user_name = data['t_zbfwb_user_name']

        print(user_name)
        user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()

        print(user)
        if user:
            db.session.delete(user)
            db.session.commit()
        else:
            print("debug2")
            # 构建响应数据
            response = {
                'message': {
                    'result': 400,  # 创建成功
                    'result_text': 'User not existed',
                    'count': 0,
                    'data': []  # 返回创建的用户数据
                }
            }
            return response

        # 构建响应数据
        response = {
            'message': {
                'result': 201,  # 创建成功
                'result_text': 'User deleted successfully',
                'count': 1,
                'data': [user]  # 返回创建的用户数据
            }
        }

        return response


# 创建用户资源
@ns1.route('/add_user_bcrypt')
class AddUserBcryptResource(Resource):
    # @jwt_required()
    @ns1.expect(user_login_model)
    @ns1.marshal_with(response_user_model)
    def post(self):
        """Create a new user with bcrypt encryption"""
        # 检查权限（假设权限是 'create_user'）
        # if not check_permission([1]):
        #     return {'message': {'result': 403, 'result_text': 'Permission denied', 'count': 0, 'data': []}}, 403

        data = api.payload

        """check username dup"""
        user_name = data['t_zbfwb_user_name']

        existing_user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
        if existing_user:
            response = {
                'message': {
                    'result': 400,  # 创建成功
                    'result_text': f'User  {user_name}  already exists',
                    'count': 1,
                    'data': [existing_user]  # 返回创建的用户数据
                }
            }
            return response

        # 生成唯一的 user_id，例如使用 UUID
        import uuid
        new_user_id = str(uuid.uuid4().int)[0:8]

        # 使用bcrypt对密码进行加密
        password = data['t_zbfwb_user_passwd'].encode('utf-8')
        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf-8')

        new_user = Zbfwbuser(
            t_zbfwb_user_id=new_user_id,
            t_zbfwb_user_name=data['t_zbfwb_user_name'],
            t_zbfwb_user_passwd=hashed_password
        )

        db.session.add(new_user)
        db.session.commit()

        # 构建响应数据
        response = {
            'message': {
                'result': 201,  # 创建成功
                'result_text': 'User created successfully',
                'count': 1,
                'data': [new_user]  # 返回创建的用户数据
            }
        }

        return response, 201


@ns1.route('/updateuser_bcrypt')
class UserUpdateBcryptResource(Resource):
    @jwt_required()
    @ns1.expect(user_login_model)
    @ns1.marshal_with(response_user_model)
    def post(self):
        """Update a user password with bcrypt encryption"""
        # 检查权限（假设权限是 'create_user'）
        if not check_permission([3]):
            return {'message': {'result': 403, 'result_text': 'Permission denied', 'count': 0, 'data': []}}, 403

        data = api.payload
        user_name = data['t_zbfwb_user_name']

        # 使用 bcrypt 加密新密码
        password = data['t_zbfwb_user_passwd'].encode('utf-8')  # 将密码转为 bytes
        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()).decode('utf-8')  # 加密并转为字符串存储

        print(f"Updating password for user: {user_name}")
        user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()

        if user:
            print("User found, updating password")
            user.t_zbfwb_user_passwd = hashed_password
            db.session.commit()
        else:
            print("User not found")
            # 构建响应数据
            response = {
                'message': {
                    'result': 400,
                    'result_text': 'User not existed',
                    'count': 0,
                    'data': []
                }
            }
            return response

        # 构建响应数据
        response = {
            'message': {
                'result': 201,
                'result_text': 'User password updated successfully with bcrypt',
                'count': 1,
                'data': [user]
            }
        }

        return response


#
# @ns1.route('/<int:user_id>')
# class UserItemResource(Resource):
#     @jwt_required()
#     def get(self, user_id):
#         """Get user by user_id"""
#         # 检查权限（假设权限是 'view_user'）
#         if not check_permission([4]):
#             return {'message': 'Permission denied'}, 403
#
#         user = Zbfwbuser.query.get(user_id)
#         if user:
#             return user
#         api.abort(404, f"User {user_id} not found")
#
#     @jwt_required()
#     def put(self, user_id):
#         """Update user by user_id"""
#         # 检查权限（假设权限是 'edit_user'）
#         if not check_permission([3]):
#             return {'message': 'Permission denied'}, 403
#
#         user = Zbfwbuser.query.get(user_id)
#         if user:
#             data = api.payload
#             user.t_zbfwb_user_passwd = data['t_zbfwb_user_passwd']
#             db.session.commit()
#             return user
#         api.abort(404, f"User {user_id} not found")
#
#     @jwt_required()
#     def delete(self, user_id):
#         """Delete user by user_id"""
#         # 检查权限（假设权限是 'delete_user'）
#         if not check_permission([2]):
#             return {'message': 'Permission denied'}, 403
#
#         user = Zbfwbuser.query.get(user_id)
#
#         if user:
#             db.session.delete(user)
#             db.session.commit()
#             return user
#         api.abort(404, f"User {user_id} not found")


@ns1.route('/find_by_name/<string:user_name>')
class UserByNameResource(Resource):
    @ns1.marshal_with(response_user_model, as_list=True)
    def get(self, user_name):
        user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
        if user:
            response = {
                'message': {
                    'result': 201,  # 创建成功
                    'result_text': 'User query successfully',
                    'count': 1,
                    'data': [user]  # 返回创建的用户数据
                }
            }
            return response
        # api.abort(404, f"User with user_name {user_name} not found")
        response = {
            'message': {
                'result': 400,  # 创建成功
                'result_text': 'User not existed',
                'count': 0,
                'data': []  # 返回创建的用户数据
            }
        }
        return response


# # 创建用户资源
# @ns1.route('/user')
# class UserResource(Resource):
#     @jwt_required()
#     @ns1.marshal_with(user_model, as_list=True)
#     def get(self):
#         # 接口描述使用  """ """
#         """Get a list of all users"""
#         users = Zbfwbuser.query.all()
#         return users
#
#     @jwt_required()
#     @ns1.marshal_with(user_model, as_list=True)
#     @ns1.expect(user_model)
#     def post(self):
#         """Create a new user"""
#         data = api.payload
#
#         """check username dup"""
#         user_name = data['t_zbfwb_user_name']
#         existing_user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
#         if existing_user:
#             api.abort(400, f"User with user_name {user_name} already exists")
#
#         # 生成唯一的 user_id，例如使用 UUID
#         import uuid
#         new_user_id = str(uuid.uuid4().int)[0:8]
#
#         new_user = Zbfwbuser(t_zbfwb_user_id=new_user_id,
#                              t_zbfwb_user_name=data['t_zbfwb_user_name'],
#                              t_zbfwb_user_passwd=data['t_zbfwb_user_passwd'])
#
#         db.session.add(new_user)
#         db.session.commit()
#         return new_user, 201
#
#
# @ns1.route('/<int:user_id>')
# class UserItemResource(Resource):
#     @jwt_required()
#     @ns1.marshal_with(user_model)
#     def get(self, user_id):
#         """Get user by user_id"""
#         user = Zbfwbuser.query.get(user_id)
#         if user:
#             return user
#         api.abort(404, f"User {user_id} not found")
#
#     @jwt_required()
#     @ns1.marshal_with(user_model, as_list=True)
#     @ns1.expect(user_model)
#     def put(self, user_id):
#         """Update user by user_id"""
#         user = Zbfwbuser.query.get(user_id)
#         if user:
#             data = api.payload
#             # 修改密码
#             user.t_zbfwb_user_passwd = data['t_zbfwb_user_passwd']
#             db.session.commit()
#             return user
#         api.abort(404, f"User {user_id} not found")
#
#     @jwt_required()
#     @ns1.marshal_with(user_model, as_list=True)
#     @ns1.expect(user_model)
#     def delete(self, user_id):
#         """Delete user by user_id"""
#         user = Zbfwbuser.query.get(user_id)
#
#         if user:
#             db.session.delete(user)
#             db.session.commit()
#             return user
#         api.abort(404, f"User {user_id} not found")
#
#
# @ns1.route('/find_by_name/<string:user_name>')
# class UserByNameResource(Resource):
#     @ns1.marshal_with(user_model, as_list=True)
#     def get(self, user_name):
#         user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
#         if user:
#             return user
#         api.abort(404, f"User with user_name {user_name} not found")


# @ns1.route('/userpage')
# class UserPageResource(Resource):
#     @jwt_required()
#     @ns1.marshal_with(page_data_model)
#     @ns1.expect(page_model)
#     def post(self):
#         """Get users by pages"""  # 接口说明紧跟在函数后面
#         pagedata = api.payload
#
#         #获取分页请求信息
#         page = pagedata['page']
#         if page < 1:
#             # default start page
#             page = 1
#         per_page = pagedata['per_page']
#         if per_page < 1:
#             # default per page
#             per_page = 10
#
#         error_out = False
#         # 最大页数
#         max_per_page = pagedata['max_page']
#
#         # query
#         pageusers = Zbfwbuser.query.paginate(page=page, per_page=per_page, error_out=error_out,
#                                              max_per_page=max_per_page)
#
#         # has_next: 是否还有下一页
#         # has_prev: 是否还有上一页
#         # items: 返回当前页的所有内容
#         # next(error_out=False): 返回下一页的Pagination对象
#         # prev(error_out=False): 返回上一页的Pagination对象
#         # page: 当前页的页码(从1开始)
#         # pages: 总页数
#         # per_page: 每页显示的数量
#         # prev_num: 上一页页码数
#         # next_num: 下一页页码数
#         # query: 返回
#         # total: 查询返回的记录总
#
#         # debug
#         # print(pageusers.page)
#         # print(pageusers.pages)
#         # print(pageusers.has_next)
#         # print(pageusers.has_prev)
#         # print(pageusers.prev_num)
#         # print(pageusers.next_num)
#         # print(pageusers.total)
#         # print(pageusers.items)
#
#         return pageusers, 200

@ns1.route('/userpage')
class UserPageResource(Resource):
    @jwt_required()
    @ns1.marshal_with(response_user_page_data_model)
    @ns1.expect(page_model)
    def post(self):
        """Get users by pages"""
        # 检查权限（假设权限是 'view_users'）
        if not check_permission([4]):
            return {
                'message': 'Permission denied',
                'result': [],
                'status': 200,
                'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }, 403

        pagedata = api.payload
        page = pagedata['page']
        if page < 1:
            page = 1
        per_page = pagedata['per_page']
        if per_page < 1:
            per_page = 10

        error_out = False
        max_per_page = pagedata['max_page']

        pageusers = Zbfwbuser.query.paginate(page=page, per_page=per_page, error_out=error_out,
                                             max_per_page=max_per_page)

        # return pageusers, 200

        response = format_response_page(
            message="用户翻页查询结果",
            result=pageusers,
            status=200,
            timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        )

        return response

# # 增加一个新的路由装饰器，允许通过 user_name 查询用户
# @api.route('/find_by_name/<string:user_name>')
# class UserByNameResource(Resource):
#     def get(self, user_name):
#         user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
#         if user:
#             return user
#         api.abort(404, f"User with user_name {user_name} not found")
#
#
# @api.route('/create')
# class UserCreateResource(Resource):
#     @api.expect(user_model)
#     def post(self):
#         """Create a new user"""
#         data = api.payload
#         user_name = data['t_zbfwb_user_name']
#         # 检查用户是否已存在
#         existing_user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
#         if existing_user:
#             api.abort(400, f"User with user_name {user_name} already exists")
#
#         # 生成唯一的 user_id，例如使用 UUID
#         import uuid
#         new_user_id = str(uuid.uuid4())
#
#         # 创建新用户
#         new_user = Zbfwbuser(t_zbfwb_user_id=new_user_id,
#                              t_zbfwb_user_name=user_name,
#                              t_zbfwb_user_passwd=data['t_zbfwb_user_passwd'])
#         db.session.add(new_user)
#         db.session.commit()
#         return new_user
#
#
# @api.route('/update/<string:user_name>')
# class UserUpdateResource(Resource):
#     @api.expect(user_model)
#     def put(self, user_name):
#         """Update user by user_name"""
#         data = api.payload
#         user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=user_name).first()
#         if user:
#             user.user_passwd = data['t_zbfwb_user_passwd']
#             db.session.commit()
#             return user
#         api.abort(404, f"User with user_name {user_name} not found")
#
#
# @api.route('/delete/<string:user_name>')
# class UserDeleteResource(Resource):
#     def delete(self, user_name):
#         """Delete user by user_name"""
#         user = Zbfwbuser.query.filter_by(t_zbfwb_user_passwd=user_name).first()
#         if user:
#             db.session.delete(user)
#             db.session.commit()
#             return {"message": f"User with user_name {user_name} has been deleted"}
#         api.abort(404, f"User with user_name {user_name} not found")
